package com.alibaba.citrus.cr.mn.order.center.facade.adapter.impl;

import com.alibaba.citrus.cr.mn.order.center.facade.adapter.BizInventoryQueryAdapter;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.request.InventoryAvailableQtyQueryRequest;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.response.InventoryAvailableQtyQueryDTO;
import com.alibaba.cloud.retail.business.inventory.api.model.BusinessInventoryQueryDTO;
import com.alibaba.cloud.retail.business.inventory.api.request.InventoryParamDetailRequest;
import com.alibaba.cloud.retail.business.inventory.api.request.InventoryParamRequest;
import com.alibaba.cloud.retail.business.inventory.api.service.BusinessInventoryReadService;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.result.Result;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.collections.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author zhangxiaorui
 * @ClassName BizInventoryQueryAdapterImpl
 * @description: TODO
 * @date 2023/05/30 19:00
 * @version: 1.0
 */
@Service
public class BizInventoryQueryAdapterImpl implements BizInventoryQueryAdapter {
    private static final Log log = Log.getLogger(BizInventoryQueryAdapterImpl.class);

    @DubboReference
    private BusinessInventoryReadService businessInventoryReadService;

    @Override
    public List<InventoryAvailableQtyQueryDTO> queryInventoryAvailableQty(List<InventoryAvailableQtyQueryRequest> requestList) {
        if (CollectionUtils.isEmpty(requestList)) {
            return Lists.newArrayList();
        }

        // 按仓合并
        Map<String, List<InventoryAvailableQtyQueryRequest>> inventoryAvailableQtyQueryRequestMap = requestList.stream()
                .collect(Collectors.groupingBy(InventoryAvailableQtyQueryRequest::getLogicWarehouseCode));

        Map<String, Set<String>> warehouseOfGoodsCodeList = Maps.newHashMap();
        inventoryAvailableQtyQueryRequestMap.forEach((warehouseCode, queryRequests) -> {
            List<String> mergeCodeList = queryRequests.stream().map(InventoryAvailableQtyQueryRequest::getGoodsCodeList)
                    .reduce(Lists.newArrayList(), (a, b) -> {
                        a.addAll(b);
                        return a;
                    });
            warehouseOfGoodsCodeList.put(warehouseCode, Sets.newHashSet(mergeCodeList));
        });

        List<InventoryParamDetailRequest> reqList = Lists.newArrayList();
        warehouseOfGoodsCodeList.forEach((warehouseCode, codeList) -> {
            InventoryParamDetailRequest req = new InventoryParamDetailRequest();
            req.setLogicWarehouseCode(warehouseCode);
            req.setGoodsCodeList(Lists.newArrayList(codeList));
            reqList.add(req);
        });

        InventoryParamRequest inventoryParamRequest = new InventoryParamRequest();
        inventoryParamRequest.setRequestList(reqList);
        try {
            Result<List<BusinessInventoryQueryDTO>> listResult = businessInventoryReadService.queryByInventoryByParam(inventoryParamRequest);
            log.info("业务库存查询 request={}, result={}", inventoryParamRequest, listResult);

            if (Objects.isNull(listResult) || CollectionUtils.isEmpty(listResult.getResult())) {
                return Lists.newArrayList();
            }
            return listResult.getResult().stream().map(p -> {
                InventoryAvailableQtyQueryDTO queryDTO = new InventoryAvailableQtyQueryDTO();
                BeanUtils.copyProperties(p, queryDTO);
                return queryDTO;
            }).collect(Collectors.toList());
        } catch (Exception e) {
            log.error("业务库存查询异常 request={}, error={}", JSON.toJSONString(inventoryParamRequest), e);
        }
        return Lists.newArrayList();
    }
}
